package org.example.quartz.BIP;

import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.quartz.service.LogService;
import org.example.quartz.service.OrgService;
import org.example.quartz.service.UtilService;
import org.example.quartz.task.QuartzTaskJob;
import org.example.quartz.util.DataSourceUtil;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
// 再Job被执行结束后，将会更新JobDataMap，这样下次Job执行后悔使用新的值而不是初始值
@PersistJobDataAfterExecution
// 同一时间将只有一个Job实例被执行，为了避免并发问题导致数据紊乱，建议这两个注解一起使用
@DisallowConcurrentExecution
public class SubjectQcQuartz_BIP implements QuartzTaskJob {


    Map<String, Object> gsMap = DataSourceUtil.getGS();
    //全局接口配置
    String IP = (String) gsMap.get("IP");
    String PORT = (String) gsMap.get("PORT");
    String ECC = (String) gsMap.get("ECC");
    String Bearer = (String) gsMap.get("Bearer");

    //日志
    LogService loginfo = SpringUtil.getBean(LogService.class);
    //orgService
    OrgService orgService = SpringUtil.getBean(OrgService.class);
    //orgService
    UtilService utilService = SpringUtil.getBean(UtilService.class);
    /**
     * 科目期初接口
     * 科目余额接口地址：GSCloud文档3.11
     * http://ip:port/api/jg/syncbddata/v1.0/bdsyncinterface/syncKmye
     **/
    @SneakyThrows
    @Override
    public void execute(JobExecutionContext context) {
        //传入变量 lastTime 最后抓取时间
        //链接BIP数据库，查询出需要同步的数据，根据TS时间进行判断。
        //TS从中间库表获取到最后一次更新时间，根据此时间进行增量查询推送；
        //中间库日志表记录推送日志，成功、失败、返回信息等（备查）
        //中间库记录最后推送数据的时间，根据时间进行下次查询的条件；
        //查询脚本
        String methodName = "SubjectQcQuartz";
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);
        //1、查询时间
        String ts = utilService.getTs(methodName, jdbcTemplate);
        String orgStr = utilService.getGSOrgStr(jdbcTemplate);
        /**
         *SELECT
         * 	org_accountingbook.code 账簿编码,
         * 	org_accountingbook.name 账簿名称,
         * 	bd_accasoa.dispname 科目名称,
         * 	sum( CASE WHEN adjustperiod = '00' THEN gl_detail.localdebitamount ELSE 0 END ) "期初借方",
         * 	sum( CASE WHEN adjustperiod = '00' THEN gl_detail.localcreditamount ELSE 0 END ) "期初贷方",
         * 	sum( CASE WHEN adjustperiod = '12' THEN gl_detail.localdebitamount ELSE 0 END ) "借方发生",
         * 	sum( CASE WHEN adjustperiod = '12' THEN gl_detail.localcreditamount ELSE 0 END ) "贷方发生",
         * 	sum( CASE WHEN adjustperiod > '00' AND adjustperiod <= '12' THEN gl_detail.localdebitamount ELSE 0 END ) "借方累计",
         * 	sum( CASE WHEN adjustperiod > '00' AND adjustperiod <= '12' THEN gl_detail.localcreditamount ELSE 0 END ) "贷方累计",
         * 	sum( CASE WHEN adjustperiod <= '12' THEN gl_detail.localdebitamount ELSE 0 END ) "借方期末",
         * 	sum( CASE WHEN adjustperiod <= '12' THEN gl_detail.localcreditamount ELSE 0 END ) "贷方期末"
         * FROM
         * 	gl_detail gl_detail,
         * 	org_accountingbook,
         * 	bd_accasoa,
         * 	bd_account
         * WHERE
         * 	gl_detail.pk_accountingbook = org_accountingbook.pk_accountingbook
         * 	AND gl_detail.pk_accasoa = bd_accasoa.pk_accasoa
         * 	AND bd_accasoa.pk_account = bd_account.pk_account
         * 	AND gl_detail.yearv = '2024'
         * 	AND gl_detail.adjustperiod >= '00'
         * 	AND gl_detail.adjustperiod <= '12'
         * 	AND org_accountingbook.code = '1001-0001'
         * 	AND gl_detail.discardflagv <> 'Y'
         * 	AND gl_detail.dr = 0
         * 	AND gl_detail.voucherkindv <> 255
         * 	AND gl_detail.tempsaveflag <> 'Y'
         * 	AND gl_detail.voucherkindv <> 5
         * 	AND 1 = 1
         * GROUP BY
         * 	gl_detail.pk_accasoa,
         * 	gl_detail.pk_accountingbook,
         * 	gl_detail.yearv,
         * 	org_accountingbook.code,
         * 	org_accountingbook.name,
         * 	bd_accasoa.dispname
         * */
        String YEAR = "2023";
        String accbook ="";
        //2、根据时间查询数据集 (停用和删除的过滤掉，暂不考虑，线下处理)
        String selectSQL = "SELECT\n" +
                " '"+YEAR+"' AS YEAR" +
                "\torg_accountingbook.code LEDGER,\n" +
                "\torg_accountingbook.name LEDGERNAME,\n" +
                "\tbd_accasoa.dispcode AS ACCTITLECODE,\n" +
                "\tbd_accasoa.dispname AS ACCTITLENAME,\n" +
                "\tsum( CASE WHEN adjustperiod = '00' THEN gl_detail.localdebitamount ELSE 0 END ) \"期初借方\",\n" +
                "\tsum( CASE WHEN adjustperiod = '00' THEN gl_detail.localcreditamount ELSE 0 END ) \"期初贷方\",\n" +
                "\tsum( CASE WHEN adjustperiod = '12' THEN gl_detail.localdebitamount ELSE 0 END ) \"借方发生\",\n" +
                "\tsum( CASE WHEN adjustperiod = '12' THEN gl_detail.localcreditamount ELSE 0 END ) \"贷方发生\",\n" +
                "\tsum( CASE WHEN adjustperiod > '00' AND adjustperiod <= '12' THEN gl_detail.localdebitamount ELSE 0 END ) \"借方累计\",\n" +
                "\tsum( CASE WHEN adjustperiod > '00' AND adjustperiod <= '12' THEN gl_detail.localcreditamount ELSE 0 END ) \"贷方累计\",\n" +
                "\tsum( CASE WHEN adjustperiod <= '12' THEN gl_detail.localdebitamount ELSE 0 END ) \"借方期末\",\n" +
                "\tsum( CASE WHEN adjustperiod <= '12' THEN gl_detail.localcreditamount ELSE 0 END ) \"贷方期末\" \n" +
                "FROM\n" +
                "\tgl_detail gl_detail,\n" +
                "\torg_accountingbook,\n" +
                "\tbd_accasoa,\n" +
                "\tbd_account \n" +
                "WHERE\n" +
                "\tgl_detail.pk_accountingbook = org_accountingbook.pk_accountingbook \n" +
                "\tAND gl_detail.pk_accasoa = bd_accasoa.pk_accasoa \n" +
                "\tAND bd_accasoa.pk_account = bd_account.pk_account \n" +
                "\tAND gl_detail.yearv = '"+YEAR+"' \n" +
                "\tAND gl_detail.adjustperiod >= '00' \n" +
                "\tAND gl_detail.adjustperiod <= '12' \n" +
                "\tAND org_accountingbook.code = '"+accbook+"' \n" +
                "\tAND gl_detail.discardflagv <> 'Y' \n" +
                "\tAND gl_detail.dr = 0 \n" +
                "\tAND gl_detail.voucherkindv <> 255 \n" +
                "\tAND gl_detail.tempsaveflag <> 'Y' \n" +
                "\tAND gl_detail.voucherkindv <> 5 \n" +
                "\tAND 1 = 1 \n" +
                "GROUP BY\n" +
                "\tgl_detail.pk_accasoa,\n" +
                "\tgl_detail.pk_accountingbook,\n" +
                "\tgl_detail.yearv,\n" +
                "\torg_accountingbook.code,\n" +
                "\torg_accountingbook.name,\n" +
                "\tbd_accasoa.dispname";
        //查询数据，根据数据结果推送给GS浪潮
        Session oracleSession = DataSourceUtil.getOracleSession();
        List<Entity> query = oracleSession.query(selectSQL);
        //拼装数据，推送给浪潮
        if(query.size()>0){
            for (Map<String, Object> gSmap : query) {
                //更换gsCode
                String gsCode = orgService.selectGsCode((String) gSmap.get("ORGCODE"),jdbcTemplate);
                String GsJson ="{\n" +
                        "\"YEAR\":\"2024\",\n" +
                        "\"LEDGER\":\"001004\",\n" +
                        "\"ACCTITLECODE\":\"1001\",\n" +
                        "\"CURRENCY\":\"01\",\n" +
                        "\"BEGINBALANCEAMT\":\"0\",\n" +
                        "\"CURCUMDRAMT\":\"0\",\n" +
                        "\"CURCUMCRAMT\":\"0\",\n" +
                        "\"DEBITAMT\":\"0\",\n" +
                        "\"CREDITAMT\":\"0\",\n" +
                        "\"ENDBALANCEAMT\":\"0\",\n" +
                        "\"BEGINBALANCEFOR\":\"0\",\n" +
                        "\"CURCUMDRFOR\":\"0\",\n" +
                        "\"CURCUMCRFOR\":\"0\",\n" +
                        "\"DEBITFOR\":\"0\",\n" +
                        "\"CREDITFOR\":\"0\",\n" +
                        "\"ENDBALANCEFOR\":\"0\",\n" +
                        "\"BEGINBALANCEQTY\":\"0\",\n" +
                        "\"CURCUMDRQTY\":\"0\",\n" +
                        "\"CURCUMCRQTY\":\"0\",\n" +
                        "\"DEBITQTY\":\"0\",\n" +
                        "\"CREDITQTY\":\"0\",\n" +
                        "\"ENDBALANCEQTY\":\"0\"\n" +
                        "}";
                GsJson = GsJson.replace("null","");
                //调用GS接口，推送给GS浪潮，获取返回值;
                //1、推送用户档案
                String gsUrl = IP+":"+PORT+"/api/jg/syncbddata/v1.0/bdsyncinterface/syncKmye";
                String returnMSG =   HttpRequest.post(gsUrl)
                        .header("Content-Type", "application/json")
                        .header("Accept-Language", "zh-CHS")
                        .header("X-ECC-Current-Tenant", ECC)
                        .header("Authorization", Bearer).timeout(200000)
                        .body(GsJson).execute().body();
                if(!returnMSG.isEmpty()){
                    JSONObject returnObj = JSONObject.parseObject(returnMSG);
                    //成功
                    if(returnObj.get("code").equals("0") ){
                        int loginsert = loginfo.loginfo(jdbcTemplate,methodName, LocalDateTime.now().toString(),"成功",GsJson,returnMSG,"","",gsUrl, (String) gSmap.get("TS"));
                        if(loginsert>0){
                            //System.out.println("日志写入成功！！");
                        }else{
                            System.out.println("日志写入失败！！");
                        }
                        //失败
                    }else if(returnObj.get("code").equals("1") ){
                        //写入日志表
                        int loginsert = loginfo.loginfo(jdbcTemplate,methodName,LocalDateTime.now().toString(),"失败",GsJson,returnMSG,"","",gsUrl, (String) gSmap.get("TS"));
                        if(loginsert>0){
                            //System.out.println("日志写入成功！！");
                        }else{
                            System.out.println("日志写入失败！！");
                        }
                    }else if(returnObj.get("code")==null && ("").equals(returnObj.get("code"))){
                        //写入日志表
                        int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常", GsJson, returnMSG, "",  (String) gSmap.get("ID"), gsUrl, (String) gSmap.get("TS"));
                        if (loginsert > 0) {
                            //System.out.println("日志写入成功！！");
                        } else {
                            System.out.println("日志写入失败！！");
                        }
                    }
                }
            }
        }else{
            System.out.println("暂无新数据推送");
        }

    }

}
